#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import logging
import os
from logging.handlers import RotatingFileHandler

from ksai.config import app_config
from ksai.context import Application


def setup_logging(app: Application, logs_path: str) -> None:
    # 设置日志格式
    formatter = logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")

    logger_level = logging.getLevelName(app_config.LOGGING_LEVEL)

    if os.path.isdir(logs_path):
        os.makedirs(logs_path, exist_ok=True)

    # 文件日志（自动轮换，最大 10MB，保留 5 个备份）
    file_handler = RotatingFileHandler(
        f'{logs_path}/app.log',  # 日志文件名
        maxBytes=app_config.LOGGING_FILE_MAX_BYTES,  # 10MB
        backupCount=app_config.LOGGING_BACKUP_COUNT
    )
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logger_level)  # 记录 WARNING 及以上级别

    # 控制台日志
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(logger_level)  # 开发时建议 DEBUG

    # 应用日志器配置
    app.logger.addHandler(file_handler)
    app.logger.addHandler(stream_handler)
    app.logger.setLevel(logger_level)  # 设置全局日志级别
